package com.nt.train.processor;
import com.nt.train.annotation.MyComponentScan;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
/**
 * https://blog.csdn.net/a718515028/article/details/122720093
 * https://blog.csdn.net/qq_42651904/article/details/122595724
 * https://blog.csdn.net/crazy_liyang/article/details/109609341
 * @author hlf
 * @version 1.0
 * @date 2022/8/11 15:51
 */
public class MyConfigrationRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 获得注解中的value （获取到指定路径）
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(
                importingClassMetadata.getAnnotationAttributes(MyComponentScan.class.getName()));
        String[] value = annotationAttributes.getStringArray("value");
        Set<String> packages = new LinkedHashSet<String>(Arrays.asList(value));

        // 获得builder，设置要动态注册的Bean，这里注册了ServicePostProcessor，
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(ServicePostProcessor.class);
        beanDefinitionBuilder.addConstructorArgValue(packages);

        // 设置注册bean名称
        String generatedName = BeanDefinitionReaderUtils.generateBeanName(beanDefinitionBuilder.getBeanDefinition(), registry, false);
        // 注册bean
        registry.registerBeanDefinition(generatedName,beanDefinitionBuilder.getBeanDefinition());

    }
}
